package com.ufind.server.facade.impl;

import com.ufind.common.response.Response;
import com.ufind.server.application.UserApplication;
import com.ufind.server.core.domain.User;
import com.ufind.server.core.exception.UserAccountIsExistedException;
import com.ufind.server.facade.UserFacade;
import com.ufind.server.facade.dto.UserDTO;
import com.ufind.server.facade.dto.request.RegisterCommand;
import com.ufind.server.facade.impl.assembler.UserAssembler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.inject.Named;

@Named
public class UserFacadeImpl implements UserFacade {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserFacadeImpl.class);

    @Inject
    private UserApplication userApplication;

    public UserDTO getUserById(Long userId) {
        return null;
    }

    /**
     * 进行注册
     * @param command
     * @return
     */
    public Response register(RegisterCommand command) {

        Response response = new Response();
        try {
            //进行数据的转化
            User user = UserAssembler.toCommandUser(command);
            Long flag = userApplication.insertUser(user);
            if (flag != null) {
                response.setCode(Response.CodeEnum.SUCCESS.code);
                response.setMsg("注册成功");
                response.setData(flag);//返回注册成功之后的id
            }
            return response;
        } catch (UserAccountIsExistedException e) {
            LOGGER.error(e.getMessage(), e);
            response.setCode(Response.CodeEnum.AUTHOR.code);
            response.setMsg("用户账号:" + command.getUsername() + "已经存在。");
            return response;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setCode(Response.CodeEnum.AUTHOR.code);
            response.setMsg("添加用户失败。");
            return response;
        }
    }
}